package cn.tansanqinger.service.topic.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tansanqinger.dao.sql.topic.CollectTopicSqlDaoImpl;
import cn.tansanqinger.dao.sql.topic.QueryTopicSqlDaoImpl;
import cn.tansanqinger.dao.sql.topic.RecordtopicSqlDaoImpl;
import cn.tansanqinger.dao.sql.topic.ReportTopicSqlDaoImpl;
import cn.tansanqinger.dao.sql.topic.ShieldTopicSqlDaoImpl;
import cn.tansanqinger.dao.sql.topic.TopicSqlDaoImpl;
import cn.tansanqinger.pojo.Collecttopic;
import cn.tansanqinger.pojo.Querytopic;
import cn.tansanqinger.pojo.Recordtopic;
import cn.tansanqinger.pojo.Reporttopic;
import cn.tansanqinger.pojo.Shieldtopic;
import cn.tansanqinger.pojo.Topic;
import cn.tansanqinger.pojo.User;
import cn.tansanqinger.service.topic.ITopicService;
import cn.tansanqinger.util.DateUtil;
import cn.tansanqinger.util.PageData;
import cn.tansanqinger.util.Tools;

@Service
public class TopicServiceImpl implements ITopicService {
	
	@Autowired
	private TopicSqlDaoImpl impl;
	@Autowired
	private RecordtopicSqlDaoImpl rimpl;
	@Autowired
	private CollectTopicSqlDaoImpl cimpl;
	@Autowired
	private QueryTopicSqlDaoImpl qimpl;
	@Autowired
	private ReportTopicSqlDaoImpl rtimpl;
	@Autowired
	private ShieldTopicSqlDaoImpl simpl;

	@Override
	public Topic randSelectTopic(HttpServletRequest request) {
		PageData pd = new PageData(request);
		String source = Tools.isEmpty(pd.get("source"));
		String ttype = Tools.isEmpty(pd.get("ttype"));
		String difficulty = Tools.isEmpty(pd.get("difficulty"));
		String classify = Tools.isEmpty(pd.get("classify"));
		String grade = Tools.isEmpty(pd.get("grade"));
		int sourceInt = -1;
		int ttypeInt = -1;
		int difficultyInt = -1;
		int classifyInt = -1;
		int gradeInt = -1;
		if (!"".equals(source)) sourceInt=Integer.parseInt(source);
		if (!"".equals(ttype)) ttypeInt=Integer.parseInt(ttype);
		if (!"".equals(difficulty)) difficultyInt=Integer.parseInt(difficulty);
		if (!"".equals(classify)) classifyInt=Integer.parseInt(classify);
		if (!"".equals(grade)) gradeInt=Integer.parseInt(grade);
		//首先读取用户加入黑名单的数据
		List<Shieldtopic> slist = simpl.selectTopic(ttypeInt, difficultyInt, classifyInt, gradeInt);
		//读取已经做了的题目
		List<Recordtopic> rlists = rimpl.selectTopic(ttypeInt, sourceInt, difficultyInt, classifyInt, gradeInt);
		//读取总题目
		List<Topic> tlists = impl.selectTopic(ttypeInt, difficultyInt, classifyInt, gradeInt);
		if(tlists.size()==0) return null;
		List<Recordtopic> rlist = new ArrayList<Recordtopic>();
		List<Topic> tlist = new ArrayList<Topic>();
		if(slist.size()!=0) {
			Shieldtopic slisttopics[] = slist.toArray(new Shieldtopic[slist.size()]);
			Arrays.sort(slisttopics, (o1,o2)->{
				if(o1.getTid()>o2.getTid()) return 1;
				return -1;
			});
			for (int i = 0,j=0; i < tlists.size(); i++) {
				if(j==slisttopics.length) {
					tlist.add(tlists.get(i));
					continue;
				}
				if(tlists.get(i).getTid()!=slisttopics[j].getTid()) tlist.add(tlists.get(i));
				if(tlists.get(i).getTid()==slisttopics[j].getTid()) j++;
			}
			if(rlists.size()!=0) {
				//给做了的题目排序
				Recordtopic recordtopics[] = rlists.toArray(new Recordtopic[rlists.size()]);
				Arrays.sort(recordtopics, (o1,o2)->{
					if(o1.getTid()>o2.getTid()) return 1;
					return -1;
				});
				/**
				 * 进行赛选
				 */
				for (int i = 0,j=0 ; i < recordtopics.length; i++) {
					if (j==slisttopics.length) {
						rlist.add(recordtopics[i]);
					}
					if(slisttopics[j].getTid()!=recordtopics[i].getTid()) rlist.add(recordtopics[i]);
					if(slisttopics[j].getTid()==recordtopics[i].getTid()) j++;
				}
			}
		} else {
			rlist = rlists;
			tlist = tlists;
		}
		if(sourceInt==0||sourceInt==2) {
			if(tlist.size()==0) return null;
			if(rlist.size()==0) return tlist.get((int)Math.random()*tlist.size());
			List<Topic> resultList = new ArrayList<Topic>();
			//给做了的题目排序
			Recordtopic recordtopics[] = rlists.toArray(new Recordtopic[rlists.size()]);
			Arrays.sort(recordtopics, (o1,o2)->{
				if(o1.getTid()>o2.getTid()) return 1;
				return -1;
			});
			for (int i = 0,j=0; i < tlist.size(); i++) {
				if(j==recordtopics.length) {
					resultList.add(tlist.get(i));
					continue;
				}
				if(tlist.get(i).getTid()!=recordtopics[j].getTid()) resultList.add(tlist.get(i));
				if(tlist.get(i).getTid()==recordtopics[j].getTid()) j++;
			}
			if(resultList.isEmpty()) return null;
			Double number = Math.random()*resultList.size();
			Integer numberInt = number.intValue();
			Topic topic = resultList.get(numberInt);
			topic.setTnumber(topic.getTnumber()+1);
			impl.modification(topic);
			return topic;
		} else if (sourceInt==1) {
			if(rlist.size()==0)return null;
			Double number = Math.random()*rlist.size();
			Integer numberInt = number.intValue();
			Topic topic = impl.selectOnt(rlist.get(numberInt).getTid());
			topic.setTnumber(topic.getTnumber()+1);
			impl.modification(topic);
			return topic;
		} else if (sourceInt==3) {
			if(tlist.size()==0)return null;
			Double number = Math.random()*tlist.size();
			Integer numberInt = number.intValue();
			Topic topic = tlist.get(numberInt);
			topic.setTnumber(topic.getTnumber()+1);
			impl.modification(topic);
			return topic;
		}
		return null;
	}

	@Override
	public PageData submitTopicResult(HttpServletRequest request) {
		PageData pd = new PageData(request);
		Topic topic = impl.selectOnt(Integer.parseInt(pd.get("tid")+""));
		User user = (User) request.getSession().getAttribute("user");
		Recordtopic recordtopic = rimpl.selectId(topic.getTid(), user.getId());
		if (recordtopic==null) {
			recordtopic = new Recordtopic();
			recordtopic.setRresult(1);
			if(topic.getTanswer().equals(pd.get("tanswer"))) recordtopic.setRresult(0);
			recordtopic.setRtime(DateUtil.getTime());
			recordtopic.setTclassify(topic.getTclassify());
			recordtopic.setTdifficulty(topic.getTdifficulty());
			recordtopic.setTgrade(topic.getTgrade());
			recordtopic.setTid(topic.getTid());
			recordtopic.setTtype(topic.getTtype());
			recordtopic.setUid(user.getId());
			rimpl.add(recordtopic);
		} else {
			recordtopic.setRresult(1);
			if(topic.getTanswer().equals(pd.get("tanswer")))recordtopic.setRresult(0);
			recordtopic.setRtime(DateUtil.getTime());
			rimpl.modification(recordtopic);
		}
		pd.put("code","-1");
		if(topic.getTanswer().equals(pd.get("tanswer")))pd.put("code","0");
		pd.put("msg",topic.getTanswer());
		return pd;
	}

	@Override
	public PageData collectTopic(HttpServletRequest request) {
		PageData pd = new PageData(request);
		User user = (User) request.getSession().getAttribute("user");
		String tid = pd.get("tid")+"";
		if(!"".equals(tid)) {
			Collecttopic collecttopic = cimpl.selectId(Integer.parseInt(tid), user.getId());
			if(collecttopic == null) {
				collecttopic = new Collecttopic();
				collecttopic.setTid(Integer.parseInt(tid));
				collecttopic.setUid(user.getId());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				collecttopic.setCtime(format.format(new Date()));
				pd = new PageData();
				if (1==cimpl.add(collecttopic)) {
					Topic topic = impl.selectOnt(Integer.parseInt(tid));
					topic.setTcollectnnumber(topic.getTnumber()+1);
					impl.modification(topic);
					pd.put("code", "0");
					pd.put("msg", "收藏成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "收藏失败");
				}
			} else {
				pd = new PageData();
				if(1==cimpl.delete(collecttopic.getCid())) {
					Topic topic = impl.selectOnt(Integer.parseInt(tid));
					topic.setTcollectnnumber(topic.getTnumber()-1);
					impl.modification(topic);
					pd.put("code", "0");
					pd.put("msg", "取消成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "取消失败");
				}
			}
		} else {
			pd = new PageData();
			pd.put("code", "-1");
			pd.put("msg", "数据异常");
		}
		return pd;
	}

	@Override
	public PageData shieldTopic(HttpServletRequest request) {
		PageData pd = new PageData(request);
		User user = (User) request.getSession().getAttribute("user");
		String tid = pd.get("tid")+"";
		if(!"".equals(tid)) {
			Shieldtopic shieldtopic = simpl.selectId(Integer.parseInt(tid), user.getId());
			if(shieldtopic == null) {
				Topic topic = impl.selectOnt(Integer.parseInt(tid));
				shieldtopic = new Shieldtopic();
				shieldtopic.setTid(topic.getTid());
				shieldtopic.setUid(user.getId());
				shieldtopic.setTclassify(topic.getTclassify());
				shieldtopic.setTdifficulty(topic.getTdifficulty());
				shieldtopic.setTgrade(topic.getTgrade());
				shieldtopic.setTtype(topic.getTtype());
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				shieldtopic.setStime(format.format(new Date()));
				pd = new PageData();
				if (1==simpl.add(shieldtopic)) {
					pd.put("code", "0");
					pd.put("msg", "屏蔽成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "屏蔽失败");
				}
			} else {
				pd = new PageData();
				pd.put("code", "-1");
				pd.put("msg", "数据异常");
			}
		} else {
			pd = new PageData();
			pd.put("code", "-1");
			pd.put("msg", "数据异常");
		}
		return pd;
	}

	@Override
	public PageData reportTopic(HttpServletRequest request) {
		PageData pd = new PageData(request);
		User user = (User) request.getSession().getAttribute("user");
		String tid = pd.get("tid")+"";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(!"".equals(tid)) {
			Reporttopic reporttopic = rtimpl.selectId(Integer.parseInt(tid), user.getId());
			if(reporttopic == null) {
				reporttopic = new Reporttopic();
				reporttopic.setTid(Integer.parseInt(tid));
				reporttopic.setUid(user.getId());
				reporttopic.setRtime(format.format(new Date()));
				reporttopic.setRmessage(pd.get("message")+"");
				pd = new PageData();
				if (1==rtimpl.add(reporttopic)) {
					Topic topic = impl.selectOnt(Integer.parseInt(tid));
					topic.setTisreport(1);
					impl.modification(topic);
					pd.put("code", "0");
					pd.put("msg", "举报成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "举报失败");
				}
			} else {
				reporttopic.setRtime(format.format(new Date()));
				reporttopic.setRmessage(pd.get("message")+"");
				pd = new PageData();
				if (1==rtimpl.modification(reporttopic)) {
					pd.put("code", "0");
					pd.put("msg", "举报成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "举报失败");
				}
			}
		} else {
			pd = new PageData();
			pd.put("code", "-1");
			pd.put("msg", "数据异常");
		}
		return pd;
	}

	@Override
	public PageData queryTopic(HttpServletRequest request) {
		PageData pd = new PageData(request);
		User user = (User) request.getSession().getAttribute("user");
		String tid = pd.get("tid")+"";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(!"".equals(tid)) {
			Querytopic querytopic = qimpl.selectId(Integer.parseInt(tid), user.getId());
			if(querytopic == null) {
				querytopic = new Querytopic();
				querytopic.setTid(Integer.parseInt(tid));
				querytopic.setUid(user.getId());
				querytopic.setQtime(format.format(new Date()));
				querytopic.setQmessage(pd.get("message")+"");
				pd = new PageData();
				if (1==qimpl.add(querytopic)) {
					Topic topic = impl.selectOnt(Integer.parseInt(tid));
					topic.setTisquery(1);
					impl.modification(topic);
					pd.put("code", "0");
					pd.put("msg", "提交成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "提交失败");
				}
			} else {
				querytopic.setQtime(format.format(new Date()));
				querytopic.setQmessage(pd.get("message")+"");
				pd = new PageData();
				if (1==qimpl.modification(querytopic)) {
					pd.put("code", "0");
					pd.put("msg", "提交成功");
				} else {
					pd.put("code", "-1");
					pd.put("msg", "提交失败");
				}
			}
		} else {
			pd = new PageData();
			pd.put("code", "-1");
			pd.put("msg", "数据异常");
		}
		return pd;
	}

	@Override
	public Collecttopic isCollectTopic(int o1, int o2) {
		return cimpl.selectId(o1, o2);
	}

	@Override
	public List<Topic> selectMessage(HttpServletRequest request) {
		String page = Tools.isEmpty(request.getParameter("page"));
		if(!"".equals(page)) {
			User user = (User) request.getSession().getAttribute("user");
			List<Collecttopic> collecttopics = cimpl.selectMessage(user.getId(), Integer.parseInt(page));
			if(!collecttopics.isEmpty()) {
				List<Topic> topics = new ArrayList<Topic>(collecttopics.size());
				for (int i = 0; i < collecttopics.size(); i++) {
					Topic topic = impl.selectOnt(collecttopics.get(i).getTid());
					topic.setTtime(collecttopics.get(i).getCtime());//收藏时间
					topics.add(topic);
				}
				return topics;
			}
		}
		return null;
	}

	@Override
	public int numberCollect(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		return cimpl.numberMessage(user.getId());
	}

	@Override
	public Topic selectTopicOne(HttpServletRequest request) {
		String tid = Tools.isEmpty(request.getParameter("id"));
		if(tid.matches("\\d+")) {
			User user = (User) request.getSession().getAttribute("user");
			Topic topic = impl.selectOnt(Integer.parseInt(tid));
			return topic.getTauid().equals(user.getId())?topic:null;
		}
		return null;
	}

	@Override
	public List<Topic> selectTeacherUpdata(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		String page = Tools.isEmpty(request.getParameter("page"));
		if(user.getJurisdiction()==1) {
			if(page.matches("\\d+")) {
				return impl.selectTeacherUpdata(user.getId(),Integer.parseInt(page));
			} else {
				return impl.selectTeacherUpdata(user.getId(),1);
			}
		} 
		return null;
	}

	@Override
	public Topic selectTeacherUpdataOne(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		String id = Tools.isEmpty(request.getParameter("id"));
		if(user.getJurisdiction()==1) {
			if(id.matches("\\d+")) {
				Topic topic = impl.selectTeacherUpdataOne(Integer.parseInt(id));
				if(topic.getTauid().equals(user.getId())) {
					return topic;
				}
			}
		} 
		return null;
	}

	@Override
	public PageData modificationTeacherUpdata(HttpServletRequest request) {
		PageData resultMap = new PageData();
		Topic topic = selectTopicOne(request);
		topic.setTmessage(Tools.isEmpty(request.getParameter("tmessage")));
		if(topic.getTtype()==1) {
			String answers[] = Tools.isEmpty(request.getParameter("answer")).split(",");
			Arrays.sort(answers);
			String answer = "";
			for (int i = 0; i < answers.length; i++) {
				answer+=answers[i];
				if(i<answers.length-1) {
					answer+=",";
				}
			}
			topic.setTanswer(answer);
		} else {
			topic.setTanswer(Tools.isEmpty(request.getParameter("answer")));
		}
		topic.setTanswerall(Tools.isEmpty(request.getParameter("answerall")));
		topic.setTdifficulty(Integer.parseInt(Tools.isEmpty(request.getParameter("difficulty"))));
		topic.setTgrade(Integer.parseInt(Tools.isEmpty(request.getParameter("grade"))));
		topic.setTclassify(Integer.parseInt(Tools.isEmpty(request.getParameter("classify"))));
		topic.setTqtime(DateUtil.getTime());
		if(impl.modification(topic)==1) {
			resultMap.put("code","0");
			resultMap.put("msg", "修改成功");
		} else {
			resultMap.put("code","-1");
			resultMap.put("msg", "修改失败");
		}
		return resultMap;	
	}

	@Override
	public PageData deleteTeacherUpdata(HttpServletRequest request) {
		PageData resultMap = new PageData();
		String id = Tools.isEmpty(request.getParameter("id"));
		if(id.matches("\\d+")) {
			Topic topic = selectTopicOne(request);
			if(topic!=null) {
				if(impl.deleteTeacherUpdata(Integer.parseInt(id))==1) {
					resultMap.put("code","0");
					resultMap.put("msg", "删除成功");
				} else {
					resultMap.put("code","-1");
					resultMap.put("msg", "删除失败");
				}
			} else {
				resultMap.put("code","-1");
				resultMap.put("msg", "数据异常");
			}
		} else {
			resultMap.put("code","-1");
			resultMap.put("msg", "数据错误");
		}
		return resultMap;
	}

	@Override
	public PageData addUpdata(HttpServletRequest request) {
		PageData resultMap = new PageData();
		Topic topic = new Topic();
		User user = (User) request.getSession().getAttribute("user");
		if(user.getJurisdiction()==1) {
			topic.setTsn(impl.serialNumber());
			topic.setTmessage(Tools.isEmpty(request.getParameter("tmessage")));
			topic.setTispopup(0);
			topic.setTisquery(0);
			topic.setTauid(user.getId());
			topic.setTnumber(0);
			topic.setTcollectnnumber(0);
			topic.setTcomment(0);
			topic.setTaudit(0);
			topic.setTisreport(0);
			topic.setTtype(Integer.parseInt(Tools.isEmpty(request.getParameter("type"))));
			if(topic.getTtype()==1) {
				String answers[] = Tools.isEmpty(request.getParameter("answer")).split(",");
				Arrays.sort(answers);
				String answer = "";
				for (int i = 0; i < answers.length; i++) {
					answer+=answers[i];
					if(i<answers.length-1) {
						answer+=",";
					}
				}
				topic.setTanswer(answer);
			} else {
				topic.setTanswer(Tools.isEmpty(request.getParameter("answer")));
			}
			topic.setTisidentity(1);
			topic.setTanswerall(Tools.isEmpty(request.getParameter("answerall")));
			topic.setTdifficulty(Integer.parseInt(Tools.isEmpty(request.getParameter("difficulty"))));
			topic.setTgrade(Integer.parseInt(Tools.isEmpty(request.getParameter("grade"))));
			topic.setTclassify(Integer.parseInt(Tools.isEmpty(request.getParameter("classify"))));
			topic.setTtime(DateUtil.getTime());
			topic.setTqtime(DateUtil.getTime());
			if(impl.add(topic)==1) {
				resultMap.put("code","0");
				resultMap.put("msg", "添加成功");
			} else {
				resultMap.put("code","-1");
				resultMap.put("msg", "添加失败");
			}
		} else {
			resultMap.put("code", "0");
			resultMap.put("msg", "账号异常");
		}
		return resultMap;
	}

	@Override
	public int topicCountAll(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if(user.getJurisdiction()==1) {
			return impl.topicCountAll(user.getId());
		}
		return 0;
	}

}
